#include <iostream>
#include <vector>
#include <cassert>

using namespace std;

// 200.岛屿数量
// 给定一个二维数组，只含有0和1两个字符。其中1代表陆地，0代表水域。
// 横向和纵向的陆地连接成岛屿，被水域分隔开。问给出的地图中有多少岛屿？

class Solution {
    int d[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};  // 位移数组
    int m,n;    // grid的行数和列数
    vector<vector<bool>> visited;   // 标记已经访问过的陆地
    // 判断坐标是否在grid范围内
    bool inArea(int x, int y) {
        return x >= 0 && x < m && y >= 0 && y < n;
    }
    // 从grid[x][y]的位置开始，进行floodfill
    // 保证(x,y)合法，且grid[x][y]是没有被访问过的陆地
    void dfs(vector<vector<char>> &grid, int x, int y) {
        visited[x][y] = true;
        for(int i = 0; i < 4; i++) {
            int newx = x + d[i][0];
            int newy = y + d[i][1];
            // 递归终止条件已经融入到下面的if判断中
            if(inArea(newx, newy) && !visited[newx][newy] && grid[newx][newy] == '1')
                dfs(grid, newx, newy);
        }
    }
public:
    int numIslands(vector<vector<char>>& grid) {
        m = grid.size();
        if(m == 0)
            return 0;
        n = grid[0].size();

        visited = vector<vector<bool> >(m, vector<bool>(n, false));

        int res = 0;
        for(int i = 0; i < m; i++)
            for(int j = 0; j < n; j++)
                if(grid[i][j] == '1' && !visited[i][j]) {
                    res++;  // 找到了新的岛屿
                    dfs(grid, i, j);    // 进行深度优先遍历，flood fill
                }

        return res;
    }
};

int main() {

    char g1[4][5] = {
            {'1','1','1','1','0'},
            {'1','1','0','1','0'},
            {'1','1','0','0','0'},
            {'0','0','0','0','0'}
    };
    vector<vector<char>> grid1;
    for(int i = 0 ; i < 4 ; i ++)
        grid1.push_back( vector<char>(g1[i], g1[i] + sizeof( g1[i])/sizeof(char)));

    cout << Solution().numIslands(grid1) << endl;
    // 1

    // ---

    char g2[4][5] = {
            {'1','1','0','0','0'},
            {'1','1','0','0','0'},
            {'0','0','1','0','0'},
            {'0','0','0','1','1'}
    };
    vector<vector<char>> grid2;
    for(int i = 0 ; i < 4 ; i ++)
        grid2.push_back(vector<char>(g2[i], g2[i] + sizeof( g2[i])/sizeof(char)));

    cout << Solution().numIslands(grid2) << endl;
    // 3
    return 0;
}
